package com.nzd.slsharing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nzd.slsharing.dto.UserDto;
import com.nzd.slsharing.mapper.UserMapper;
import com.nzd.slsharing.pojo.*;
import com.nzd.slsharing.service.*;
import com.nzd.slsharing.util.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

import static com.nzd.slsharing.util.ResultCodeEnum.ARGUMENT_VALID_ERROR;
import static com.nzd.slsharing.util.ResultCodeEnum.LOGIN_NOUSER;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private LearningExchangService learningExchangService;
    @Resource
    private LifeSharingService lifeSharingService;
    @Resource
    private CommentService commentService;
    @Resource
    private LikeService likeService;


    @PostMapping("/Login")
    public Result userLogin(@RequestBody LoginForm LoginForm) throws Exception {
        //创建一个用户用于接收
        User user = new User();
        //创建一个dto用于返回前端；
        UserDto userDto=new UserDto();
        //判断用户账号,密码、学号是否为空
        if (!Strings.isEmpty(LoginForm.getPassword())&&!Strings.isEmpty(LoginForm.getUsername())&&!Strings.isEmpty(LoginForm.getStudentId())) {
            System.out.println("1");
            //查询用户是否存在
            user=userService.getUserByStudentIdAndUP(LoginForm.getStudentId(),LoginForm.getUsername(), EncryptionUtils.encrypt(LoginForm.getPassword()));
         if(user==null) {
             return Result.build(LOGIN_NOUSER);
         }else {
            //用户存在,生成token
             //对象复制
            BeanUtils.copyProperties(user, userDto);
             userDto.setCreateTime(new Date());
             userDto.setUpdateTime(null);
             userDto.setAuthorization(JwtHelper.generateToken(user.getStudentId(),user.getUsername()));
         }
        }else {
            return Result.build(ARGUMENT_VALID_ERROR);
        }
        return Result.ok(userDto);
    }

    @PostMapping("/register")
    public Result userRegister(@RequestBody RegisterForm registerForm) {
        return Result.ok(userService.register(registerForm));
    }


    //获取用户信息
    @GetMapping("/info")
    public Result getUserInfo(HttpServletRequest request) {
        // 从请求头中提取学生 ID 和用户名
        String studentId = AuthContextHolder.getStudentIdFromToken(request);
//        String username = AuthContextHolder.getUsernameFromToken(request);

        // 如果 token 不存在或格式不正确，返回 401 Unauthorized 错误
        if (studentId == null ) {
            return Result.fail();
        }

        // 如果 token 有效，返回用户信息
      User user =userService.getUserByStudentId(studentId);
//        UserDto userDto=new UserDto();
//        //对象复制
//        BeanUtils.copyProperties(user, userDto);
        return Result.ok(user);
    }

    //查询用户信息
    @GetMapping("/getByStudentId")
    public Result getUserByStudentId(@RequestParam String studentId) {
        if (studentId == null || studentId.isEmpty()) {
            return Result.fail("StudentId is required");
        }

        try {
            // 获取用户信息
            User user = userService.getUserByStudentId(studentId);
            if (user == null) {
                return Result.fail("User not found");
            }

            // 解密用户密码
            String decryptedPassword = EncryptionUtils.decrypt(user.getPassword());

            user.setPassword(decryptedPassword);
            return Result.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("Decryption error");
        }
    }


    //修改用户信息
    @PutMapping("/updateByStudentId")
    public Result updateByStudentId(@RequestBody User user) throws Exception {
        //加密密码
        String Password=EncryptionUtils.encrypt(user.getPassword());
        user.setPassword(Password);
        user.setUpdateTime(new Date());
       return Result.ok(userService.updateById(user));
    }


    //查询用户列表
    @GetMapping("/list")
    public Result list() {
      return Result.ok(userService.list());
    }

    //查询用户列表 带分页
    @GetMapping("/pageList")
    public Result pageList(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                           @RequestParam(required = false, defaultValue = "3") Integer pageSize,@RequestParam(required = false, defaultValue = "") String name) {
        // 设置分页参数
        Page<User> page = new Page<>(pageNum, pageSize);
        QueryWrapper <User>  queryWrapper=new QueryWrapper<>();
        queryWrapper.like("username",name);
        return Result.ok(userService.page(page,queryWrapper));
    }

    //删除
    @DeleteMapping("/{id}")
    public Result del(@PathVariable String id) {
        //删除关联的帖子
        QueryWrapper<LearningExchange> queryWrapper=new QueryWrapper<>();
        QueryWrapper<LifeSharing> queryWrapper1=new QueryWrapper<>();
        QueryWrapper<Comment> queryWrapper2=new QueryWrapper<>();
        QueryWrapper<Like> queryWrapper3=new QueryWrapper<>();
        queryWrapper.eq("author",id);
        queryWrapper1.eq("author",id);
        queryWrapper2.eq("student_id",id);
        queryWrapper3.eq("like_user_id",id);
        List<LearningExchange> learningExchanges=  learningExchangService.list(queryWrapper);
        List<LifeSharing> lifeSharings=  lifeSharingService.list(queryWrapper1);
        List<Comment> Comments=  commentService.list(queryWrapper2);
        List<Like> likes=  likeService.list(queryWrapper3);
        for (LearningExchange learningExchange : learningExchanges) {
            learningExchangService.removeById(learningExchange.getId());
        }
        for (LifeSharing lifeSharing:lifeSharings){
            lifeSharingService.removeById(lifeSharing.getId());
        }
        for (Comment comment:Comments){
            commentService.removeById(comment.getId());
        }
        for (Like like:likes){
            likeService.removeById(like.getLikeId());
        }
        return Result.ok(userService.removeByStudentId(id));
    }

    @PutMapping("/update")
    public Result update(@RequestBody User user){
        user.setUpdateTime(new Date());
    return Result.ok(userService.updateById(user));
    }
}

